package org.wishwork.api.product.common.item.query;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wishwork.api.Api;
import org.wishwork.api.product.common.item.query.response.CommonProductItemQueryResponse;
import org.wishwork.context.Context;
import org.wishwork.helper.HttpHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 普通商品查询 按款查询
 * @author: WangYX
 * @create: 2022-04-11 11:07
 * @Version: 1.0.0
 **/

public class CommonProductItemQueryApi extends Api<List<CommonProductItemQueryResponse>, CommonProductItemQueryRequest> {

    private static final Logger log = LoggerFactory.getLogger(CommonProductItemQueryApi.class);

    private Context context;

    public CommonProductItemQueryApi(Context context) {
        this.context = context;
    }

    @Override
    protected String query(CommonProductItemQueryRequest commonProductItemQueryRequest) throws Exception {
        String url = "/open/mall/item/query";
        Map<String, Object> params = new HashMap<>();
        if (commonProductItemQueryRequest.getIIds() != null && commonProductItemQueryRequest.getIIds().size() > 0) {
            params.put("i_ids", commonProductItemQueryRequest.getIIds());
        }
        return HttpHelper.sendRequest(commonProductItemQueryRequest, params, url);
    }

    @Override
    protected List<CommonProductItemQueryResponse> process(JSONObject data, CommonProductItemQueryRequest commonProductItemQueryRequest) throws Exception {
        JSONArray datas = data.getJSONArray("datas");
        List<CommonProductItemQueryResponse> commonProductItemQueryResponses = datas.toJavaList(CommonProductItemQueryResponse.class);
        Boolean has_next = data.getBoolean("has_next");
        if (has_next) {
            Integer pageIndex = commonProductItemQueryRequest.getPageIndex();
            CommonProductItemQueryRequest build = commonProductItemQueryRequest.toBuilder().pageSize(++pageIndex).build();
            List<CommonProductItemQueryResponse> business = business(build);
            commonProductItemQueryResponses.addAll(business);
        }
        return commonProductItemQueryResponses;
    }
}
